package com.jbarreto.vc.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Servlet Filter implementation class ValidationAccessFilter
 */
public final class ValidationAccessFilter implements Filter {

	static final Log log = LogFactory.getLog(ValidationAccessFilter.class);
	
	private FilterConfig filterConfig = null;
    /**
     * Default constructor. 
     */
    public ValidationAccessFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	    long start = System.currentTimeMillis();
	    String address =  request.getRemoteAddr();
	    String file = ((HttpServletRequest) request).getRequestURI();
	    
	    HttpSession session = ((HttpServletRequest) request).getSession(false);
	    if(session == null){
	    	log.debug("The session has expired, access denied.");
	        PrintWriter out = response.getWriter();

	    	//((HttpServletResponse) response).sendRedirect("index.html");
	    	//out.print(String.format(StringResult.OP_CODE_RESULT, CodeResult.INVALID_SESSION.getcode()));
	    	return;
	    	
	    }else {
	    	
	    	log.debug(" * * * Existing User * * * ");
	    	log.debug("userId" + session.getAttribute("userId"));
	    	log.debug("permisos" + session.getAttribute("permisos"));
		}
	    log.debug(" User IP: " + address);
	    log.debug(" Resource: " + file);
	    log.debug("session.getId(): " + session.getId());
	    
	    chain.doFilter(request, response);

	    filterConfig.getServletContext().log(
	        "User access! " +      
	        " User IP: " + address +      
	        " Resource: " + file + 
	        " Milliseconds used: " + (System.currentTimeMillis() - start) 
	    );

	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
	    this.filterConfig = filterConfig;
	}

}
